package com.qf.ftp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/20
 */
public class SocketChannelHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    String path="E:\\mySelf";

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest request) throws Exception {
        String name = request.method().name();
        String uri = request.uri();
        if(!"GET".equals(name)){
            reqError(channelHandlerContext,"只支持GET类型");
            return;
        }
        File file = new File(path+uri);
        if(!file.exists()){
            reqError(channelHandlerContext,"文件不存在");
            return;
        }

        //判断file是文件还是目录
        if(file.isDirectory()){
            showDirectory(channelHandlerContext,file,uri);
        } else {
            showDirectoryFile(channelHandlerContext,file);
        }
    }

    private void showDirectoryFile(ChannelHandlerContext channelHandlerContext, File file) {
        try {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 10);
            FileChannel channel = new FileInputStream(file.getAbsoluteFile()).getChannel();
            StringBuffer stringBuffer = new StringBuffer();
//            stringBuffer.append("<html><head><meta charset='utf-8'></head>");
            while (channel.read(byteBuffer)!=-1){
                byteBuffer.flip();
                stringBuffer.append(new String(byteBuffer.array()));
                byteBuffer.clear();
            }
//            stringBuffer.append("</html>");
            respContent(channelHandlerContext,stringBuffer.toString());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showDirectory(ChannelHandlerContext channelHandlerContext, File file,String uri) throws Exception{
        File[] files = file.listFiles();
        String html ="<html><head><meta charset='utf-8'></head>";
        for (int i=0;i<files.length;i++){
            if("/".equals(uri)){
                html+="<li><a href='"+uri+files[i].getName()+"'>"+files[i].getName()+"</a></li>";
            } else{
                html+="<li><a href='"+uri+File.separator+files[i].getName()+"'>"+files[i].getName()+"</a></li>";
            }
        }
        html+="</html>";
        respContent(channelHandlerContext,html);
    }

    private void respContent(ChannelHandlerContext channelHandlerContext, String html) throws UnsupportedEncodingException {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

        response.headers().add("ContextType","text/html;charset=utf-8");

        response.content().writeBytes(html.getBytes("utf-8"));

        channelHandlerContext.channel().writeAndFlush(response);
    }

    public void reqError(ChannelHandlerContext channelHandlerContext,String content) throws UnsupportedEncodingException {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.headers().add("ContextType","text/html;charset=utf-8");
        String html = "<html><head><meta charset=\"utf-8\"></head><body><h1>只支持GET类型</h1></body></html>";

        response.content().writeBytes(html.getBytes("utf-8"));

        channelHandlerContext.channel().writeAndFlush(response);
    }
}
